<template>
  <h1>发微博页面</h1>
  <div style="width: 500px;margin: 0 auto">
    <el-input v-model="weibo.content" placeholder="微博正文"></el-input>

    <!--    图片上传开始
        file-list="fileList"  fileList是一个响应式数组
        name = "file" file指的是后端接收的属性值
    -->
    <el-upload
        v-model:file-list="fileList"
        action="http://localhost:8080/v1/upload"
        name="file"
        limit="9"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
    >
      <el-icon>
        <Plus/>
      </el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image"/>
    </el-dialog>
    <!--    图片上传结束-->

    <!--  @click="post" 如果Post方法不传参,后面的小括号可以省略不写   -->
    <el-button type="primary" @click="post"
               style="width: 100px; margin: 10px; font-weight: bold">发布
    </el-button>
  </div>
</template>

<script setup>
import {ref} from "vue";
import router from "@/router";
import qs from "qs";
import axios from "axios";
import {ElMessage} from "element-plus";
//  这个引入的是加号图标
import {Plus} from '@element-plus/icons-vue'

// 图片上传开始
const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
//   1.得到要删除的图片路径Url uploadFile就是我们要删除的那个文件对象
  let imgUrl = uploadFile.response.data;
//   2.给后端发送请求,删除图片
  axios.post("http://localhost:8080/v1/remove?imgUrl="+imgUrl)
      .then((response)=>{
        if (response.data.code==2002){
          ElMessage.success('删除成功!');
        }
     })
}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

// 图片上传结束

const weibo = ref({content: ''});
const post = () => {
  //  JSON.parse 将js对象转化为JSON格式的字符串,也就是说user变为了字符串
  //  localStorage存储数据使用 JSON.stringify()
  //              读取数据使用 JSON.parse()
  let user = getUser();
  if (user == null) {
    alert('请先登录');
    router.push('/login');
    return;
  }
  // 判断是否上传图片
  if (fileList.value.length > 0) {
    let imgUrls = []; //准备数组,用来存放多张照片
    for (let file of fileList.value) {
      //   依次得到每张照片的路径,就存入ImgUrls数组中
      let imgUrl = file.response.data;
      //   每次得到一个路径,就存入ImgUrl数组中
      imgUrls.push(imgUrl);
    }
    //   循环结束,得到的所有图片途径,将路径赋值给weibo对象
    weibo.value.imgUrls= imgUrls.toString();
  }


  // 给JSON对象赋值,需要 [对象名].value.[属性名]
  weibo.value.userId = user.id;
  //  将JSON对象转化为字符串,方便 axios与后端交互
  let data = qs.stringify(weibo.value);
  console.log(data);

  axios.post('http://localhost:8080/v1/weibos/add-new', data)
      .then((response) => {
        if (response.data.code == 2002) {
          ElMessage.success('发布成功!');
          router.push('/');
        }
      })
}

</script>

<style scoped>

</style>